package com.atguigu.gulimall.cart.config;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.LoginRespEntity;
import com.atguigu.gulimall.cart.controller.CartController;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Classname CartInterceptor
 * @Description 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 * @Date 2021/9/24 11:14
 * @Author Anonymous
 */
@SuppressWarnings("All")
public class CartInterceptor implements HandlerInterceptor {
    //ThreadLocal用完之后要清空，防止内存泄漏？ThreadLocal是强引用？
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 执行之前，
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        //因为封装的时候setAttribute时候v是封装的LoginRespEntity，所以直接强转即可
        LoginRespEntity attribute = (LoginRespEntity) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            //说明已经登录
            userInfoTo.setUserId(attribute.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            //说明有cookie
            for (Cookie cookie : cookies) {
                //user-key
                String cookieName = cookie.getName();
                if (cookieName.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    //设置为有临时用户信息
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //第一次使用购物车无论登录与否都要分配一个临时用户,如果没有临时用户一个要 分配一个临时用户，而且要命令浏览器将这个分配的cookie保存
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            //如果临时用户为空
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        //目标方法执行之前，
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 执行完毕之后分配临时用户让浏览器保存
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //如果没有临时用户一定要保存一个临时用户
        if (!userInfoTo.isTempUser()) {
            //如果没有临时用户信息，才给它放cookie
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            //设置cookie的作用域
            cookie.setDomain("gulimall.com");
            //设置cookie的最大过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME_OUT);
            response.addCookie(cookie);
        }
    }
}
